package com.atguigu.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        // 2、组装树形结构
        List<CategoryEntity> result = entities.stream().filter(e -> e.getParentCid() == 0).map(e -> {
            e.setChildren(getChildren(e, entities));
            return e;
        }).sorted((e1, e2) -> {
            return (e1.getSort() == null ? 0 : e1.getSort()) - (e2.getSort() == null ? 0 : e2.getSort());
        }).collect(Collectors.toList());

        return result;
    }

    /**
     * 递归查找
     *
     * @param root 父节点
     * @param all  所有元素
     * @return 排好序的集合
     */
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> result = all.stream()
                .filter(e -> e.getParentCid().equals(root.getCatId()))
                .map(e -> {
                    // 找到子菜单，递归
                    e.setChildren(getChildren(e, all));
                    return e;
                })
                .sorted((e1, e2) -> {
                    return (e1.getSort() == null ? 0 : e1.getSort()) - (e2.getSort() == null ? 0 : e2.getSort());
                }).collect(Collectors.toList());


        return result;
    }
}
